// src/components/countdown/index.js
import  qiniuUploader  from '../../utils/qiniuUploader'
import $config from '../../config/index'
import {
  AppModel
} from '../../models/app'
const appModel = new AppModel()

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    imgNum: Number,
    urlName:String,
    Imglist:{
      type:Array,
      observer: function (newVal, oldVal, changedPath) {
        // 属性被改变时执行的函数（可选），也可以写成在methods段中定义的方法名字符串, 如：'_propertyChange'
        // 通常 newVal 就是新设置的数据， oldVal 是旧数据
        this.Imglist = newVal
      }
    },
    // Imglist:Array
  },

  /**
   * 组件的初始数据
   */
  data: {
    Imglist: [],
    token:'',
    
  },

  

  attached: function() {
    this.initQiniu();
    
  },

  /**
   * 组件的方法列表
   */
  methods: {

    // 初始化七牛相关参数
    initQiniu: function () {
      const params = {
        bucket: $config['web-others'].bucket 
      }
      appModel.getQiniuUptoken(params).then(res => {
        const urlName = this.properties.urlName
        var options = {
          region: 'ECN', // 华北区
          // uptokenURL: 'https://[yourserver.com]/api/uptoken',
          uptoken: res.upToken,
          domain: $config['web-others'].domain ,
          shouldUseQiniuFileName: false,
          qiniuImageURLPrefix: '/weapp/service/',
          urlName:urlName
          // qiniuImageURLPrefix:'/weapp/comment/'
        };
        qiniuUploader.init(options);
      }).catch();
    },

    //移除图片
    close(e) {
      const self = this;
      const idx = e.currentTarget.dataset.index;
      self.data.Imglist.splice(idx, 1);
      self.setData({
        Imglist: self.data.Imglist
      })
      self.triggerEvent('ImgUpload', self.data.Imglist)
    },



    //上传图片
    upload(e) {
      var self = this;
      wx.chooseImage({
        count: self.properties.imgNum-self.data.Imglist.length,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success (res) {
          // tempFilePath可以作为img标签的src属性显示图片
          
          // const filePath = res.tempFilePaths[0];
          // 交给七牛上传
          for (var i = 0; i < res.tempFilePaths.length; i++){
            const filePath = res.tempFilePaths[i];
            qiniuUploader.upload(filePath, (res) => {
              console.log(res.imageURL)
              self.data.Imglist.push(res.imageURL);
              self.setData({
                Imglist:self.data.Imglist
              });
              self.triggerEvent('ImgUpload', self.data.Imglist)
            }, (error) => {
              console.error('error: ' + JSON.stringify(error));
            },
            // , {
            //     region: 'NCN', // 华东区
            //     uptokenURL: 'https://[yourserver.com]/api/uptoken',
            //     domain: 'http://[yourBucketId].bkt.clouddn.com',
            //     shouldUseQiniuFileName: false
            //     key: 'testKeyNameLSAKDKASJDHKAS'
            //     uptokenURL: 'myServer.com/api/uptoken'
            // }
            null,// 可以使用上述参数，或者使用 null 作为参数占位符
            (progress) => {
              // console.log('上传进度', progress.progress)
              //   console.log('已经上传的数据长度', progress.totalBytesSent)
              //   console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
            }, cancelTask => self.setData({cancelTask})
            );
          }
          
        }
      })
    }
  }
})
